package service

import (
	"context"
	"errors"
	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
	"mall-portalv2/global"
	utils_jwt "mall-portalv2/library/utils.jwt"
	"time"
)

func (s *Service) RedisServiceSet(ctx context.Context, key string, value interface{}, duration time.Duration) error {
	if err := s.dao.RedisDaoSet(ctx, key, value, duration); err != nil {
		return err
	}
	return nil
}

func (s *Service) RedisServiceGet(ctx context.Context, key string) ([]byte, error) {
	result, err := s.dao.RedisDaoGet(ctx, key)
	if err != nil {
		if err == redis.Nil {
			jiachaoResult, err := utils_jwt.GetJiaChaoInfo(key)
			if err != nil {
				global.Log.Error("请求家超用户体系错误", zap.Any("err", jiachaoResult))
				return result, err
			}

			if jiachaoResult.Code == 1 {
				// TODO: 存key到redis
				if err := s.RedisServiceSet(context.Background(), key, jiachaoResult.Result.UserKey, time.Hour*24); err != nil {
					global.Log.Error("redis存储出了点错误", zap.Error(err))
					return result, err
				}
				return []byte(jiachaoResult.Result.UserKey), nil
			} else {
				global.Log.Error("请求家超用户体系错误", zap.Any("err", jiachaoResult))
				return result, errors.New(jiachaoResult.Message)
			}

		} else {
			return result, err
		}
	}
	return result, nil
}
